/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.planeteVelo.bean;

import com.planeteVelo.backedBean.Client;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;

import javax.annotation.Resource;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author apo
 */
@Named
@RequestScoped
public class ClientBean {

    private Client client = new Client();
    private List<Client> lesClients = new ArrayList();
    @PersistenceContext
    EntityManager em;
    @Resource
    UserTransaction tx;

   @PostConstruct
    public void init() {

        Query query = em.createQuery("SELECT c FROM Client c");
        lesClients = query.getResultList();

    }

    public void ajouterClient() {

        System.out.println(this.client.getNom());
        FacesMessage message = null;

        message = new FacesMessage("Ajout validé");
        //ajouter le message JSF
        FacesContext.getCurrentInstance().addMessage(null, message);
        try {
            tx.begin();
            em.persist(this.client);
            tx.commit();

        } catch (Exception ex) {
            System.out.println(ex);
        }
        init();
    }
public void modifierClient(Client c) {
        FacesMessage message = null;
    message = new FacesMessage("Modification validée");
    //ajouter le message JSF
    FacesContext.getCurrentInstance().addMessage(null, message);
        try {
            tx.begin();
            em.persist(em.merge(c));
            tx.commit();
            
        }
         catch(Exception ex)
                {
                System.out.println(ex);
                }
    }

public void supprimerClient(Client c) {
    FacesMessage message = null;
    message = new FacesMessage("Suppression validée");
    //ajouter le message JSF
    FacesContext.getCurrentInstance().addMessage(null, message);
        try {
            tx.begin();
            em.remove(em.merge(c));
            tx.commit();
            em.close();
        }
         catch(Exception ex)
                {
                System.out.println(ex);
                }
      init();
}

    public Client getClient() {
        return client;
    }

    public List<Client> getLesClients() {
        return lesClients;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public void setLesClients(List<Client> lesClients) {
        this.lesClients = lesClients;
    }
}
